const BASE_URL = '/cgi-bin/';

$.fn.serializeObject = function() {
	var o = {};
	var a = this.serializeArray();
	$.each(a, function() {
		if (o[this.name]) {
			if (!o[this.name].push) {
				o[this.name] = [o[this.name]];
			}
			o[this.name].push(this.value || '');
		} else {
			o[this.name] = this.value || '';
		}
	});
	return o;
};

// Alert
window._alert = window.alert

window.alert = function(info, callback){
  if(typeof info == "string"){
    Swal.fire({
      customClass: {
        confirmButton: 'btn btn-primary btn-sm',
        cancelButton: 'btn btn-secondary btn-sm'
      },
      buttonsStyling: false,
      title: '提示',
      text: info,
      confirmButtonText: '&nbsp;&nbsp;确&nbsp;&nbsp;定&nbsp;&nbsp;'
    }).then(function(ret){
      if(typeof callback == "function") callback(ret)
    })
  }else{
    return Swal.fire(info)
  }
}

// 解析URL
function parseURL(url) {
  var a = document.createElement('a');
  a.href = url;
  return {
    source: url,
    protocol: a.protocol.replace(':', ''),
    host: a.hostname,
    port: a.port,
    query: a.search,
    params: (function() {
      var ret = {},
      seg = a.search.replace(/^\?/, '').split('&'),
      len = seg.length,
      i = 0,
      s;
      for (; i < len; i++) {
        if (!seg[i]) {
          continue;
        }
        s = seg[i].split('=');
        ret[s[0]] = s[1];
      }
      return ret;
    })(),
    file: (a.pathname.match(/\/([^\/?#]+)$/i) || [, ''])[1],
    hash: a.hash.replace('#', ''),
    path: a.pathname.replace(/^([^\/])/, '/$1'),
    relative: (a.href.match(/tps?:\/\/[^\/]+(.+)/) || [, ''])[1],
    segments: a.pathname.replace(/^\//, '').split('/')
  }
}
var URL_PARTS = parseURL(location.href);

//加载提示
var loadingIndicatorCount = 0;
function loadingIndicator(show) {
  if (show) {
    loadingIndicatorCount++;
    var domLoadingIndicator = document.querySelector('.loading-indicator');
    if (!domLoadingIndicator) {
      domLoadingIndicator = document.createElement('div');
      domLoadingIndicator.className = "loading-indicator";
      domLoadingIndicator.innerHTML = '<div><i class="fas fa-circle-notch fa-spin fa-3x fa-fw margin-bottom"></i><br/>加载中...</div>';
      document.body.appendChild(domLoadingIndicator);
    }
    domLoadingIndicator.style.display = "block";
  } else {
    loadingIndicatorCount--;
    if (loadingIndicatorCount <= 0 && document.querySelector('.loading-indicator')) document.querySelector('.loading-indicator').style.display = "none";
  }
}

// 刷新验证码
function refreshCheckCode($domCheckCode, type){
  let src = BASE_URL + "validimg.asp?id="+type+"&s=" + new Date().getTime();
  $domCheckCode.setAttribute('src', src);
}

function initCheckCode(type){
  // 验证码图片
  let $domCheckCode = document.getElementById('checkImg');
  if($domCheckCode){
  
  $domCheckCode.addEventListener('click', () => {
    refreshCheckCode($domCheckCode, type);
  })
  $domCheckCode.nextElementSibling.addEventListener('click', () => {
    refreshCheckCode($domCheckCode, type);
  })
  refreshCheckCode($domCheckCode, type);
  }
}

function callHelp(){
  alert('忘记用户名，请联系客服，详见登录页下方的提示信息！');
}

function updateWelcome(userName){
  if(userName) sessionStorage.setItem('userName', userName);
  var welcomDom = document.getElementById('left-nav-welcome');
  if(welcomDom) welcomDom.innerText = `欢迎登录，${sessionStorage.getItem('userName')}！`;
}

function logout(){
  sessionStorage.removeItem('userToken');
  location.href = "index.html";
}

// --- 数据接口：Start --- //

// 附带验证码提交
submitWithVCode = function(formData){
  var url = this.getAttribute('_action');
  return new Promise((resolve, reject) => {
    axios.post(url,{
      rows: JSON.stringify([formData]),
      yzm: formData.validationCode,
      download: 1
    }).then(function(res){
      var retData = res.data || {};
      resolve(retData);
    });
  });
}

function whatCanIDo(category){
  return new Promise((resolve, reject) => {
    axios.get('/cgi-bin/interfaceMgr/validateDate.'+category + '?rnd=' + (new Date().getTime()))
      .then(function(res){
        var retData = res.data || {};
        if(retData.kfdh) localStorage.setItem('helpTel', retData.kfdh);
        resolve(retData);
      });
  });
}

// ajax拦截
axios.interceptors.request.use(function (config) {
  // x-json
  //除登录外，所有请求都加密
  if(config.url.indexOf('/validateLogin.asp') == -1 && config.url.indexOf('uploadPic.post') == -1){
    config.headers.post['Content-Type'] = 'application/x-json';
    config.data = AJAX_COMPRESS_FN(JSON.stringify(config.data));
  }

  // 加载提示器
  if(config.url.indexOf('/hb.asp') == -1) loadingIndicator(true);

  return config;
}, function (error) {
  return Promise.reject(error);
});
axios.interceptors.response.use(function (response) {
  // 加载提示器
  loadingIndicator(false);
  
  try{
    if(response.data.clientAction == 'logout'){
      if(sessionStorage.getItem('userToken')){
        alert('登录过期，请重新登录！', logout);
      }else{
        logout();
      }
    }
  }catch(e){}

  return response;
}, function (error) {
  return Promise.reject(error);
});

// --- 数据接口：End --- //

let initCenter = {};


// --- 邮件确认页初始化：End --- //
initCenter.pageActivation = function(){
  if(URL_PARTS && URL_PARTS.params && URL_PARTS.params.mail){
    document.getElementById('email-address').innerText = URL_PARTS.params.mail
  }
}
// --- 邮件确认页初始化：End --- //

// --- 登录/下载页初始化：Start --- //
initCenter.pageDownload = function(){
  sessionStorage.removeItem('userToken');
  $('#section-login').removeClass('d-none');
  $('#section-download').addClass('d-none');
}

initCenter.formLogin = function(formData){
  var data = {
    username: formData.user,
    password: formData.mm,
    logintype: "outside",
    category: 3,
    project: null,
    token: null,
  };
  if (window.encodeAes instanceof Function) {
    var keyStr = String(new Date().valueOf());
    keyStr = encodeAes(keyStr, keyStr).toString().replace(/[^\w]/g, '').substr(0, 16);
    data = {
      data: encodeAes(JSON.stringify(data), keyStr),
      key: keyStr
    };
  }

  axios.post(this.getAttribute('_action'),data)
    .then(function(res){
      var retData = res.data || {};
      if(retData.success){
        sessionStorage.setItem('userToken', keyStr);
        updateWelcome(retData.emsg.name);

        for(var key in retData.emsg){
          var td = document.querySelector('td[name="'+key+'"]');
          if(td) td.innerText = retData.emsg[key];
        }

        if(retData.emsg.downloadurl){
          document.getElementById('pdf-viewer').classList.remove('d-none');
          document.getElementById('pdf-viewer-link').setAttribute('href', '/upload/' + retData.emsg.downloadurl);
          document.getElementById('pdf-viewer-link').setAttribute('download', '贵州特岗教师招聘准考证_' + retData.emsg.name + '.docx');
        }

        $('#section-login').addClass('d-none');
        $('#section-download').removeClass('d-none');
      }else{
        sessionStorage.removeItem('userToken');
        $('#section-login').removeClass('d-none');
        $('#section-download').addClass('d-none');

        if(retData.emsg){
          let emsg = retData.emsg;
          if(retData.code){
            switch(retData.code){
              case 'ERR_ARG_PARSE':
                break;
              case 'ERR_NO_USERNAME':
                break;
              case 'ERR_NO_PASSWORD':
                break;
              case 'ERR_GET_USERDATA':
                emsg = '不好意思，服务器正忙，请稍后再试！';
                break;
              case 'ERR_NO_USERDATA':
                emsg = '请输入正确的用户名，如果忘记用户名，请联系客服处理！';
                break;
              case 'ERR_NO_REG_FORM':
                emsg = '您未通过资格审查，无法下载准考证，有问题请联系客服';
                break;
              case 'ERR_USERDATA_PARSE':
                emsg = '您的准考证数据有错，请联系客服重新生成！';
                break;
              case 'ERR_PASSWORD_MISMATCH':
                emsg = '您密码输入错误，请重试或点击忘记密码重置！';
                break;
              case 'ERR_PASSWORD_MATCHEX':
                emsg = '您的准考证数据有误，请联系客服重新生成！';
                break;
            }
          }

          alert(emsg, function(){
            location.href = 'index.html' // 'index.html?r=' + (new Date().getTime())
          });
        }
      }

    });
}
// --- 登录/下载初始化：End --- //

// --- 找回密码页初始化：Start --- //
initCenter.pageForgetPsw = function(){
  initCheckCode('tgretrievepassword');
  whatCanIDo(3).then(function(ret){
    if(!ret.success){
      if(ret.err) document.querySelector('#alert-can-not-enroll > .alert-text').innerText = ret.err;
      document.getElementById('alert-can-not-enroll').classList.remove('d-none');
      var btnSubmit = document.querySelector('button[type="submit"]');
      btnSubmit.setAttribute('disabled','disabled');
      btnSubmit.innerText = '暂未开放！'
    }
  })
}
initCenter.formForgetPsw = function(formData){
  formData.category = 3;
  submitWithVCode.call(this, formData).then(function(retData){
    if(retData.success){
      location.href = 'activation.html';
    }else{
      if(typeof retData.emsg == "string") alert(retData.emsg);
    }
  })
}
// --- 找回密码初始化：End --- //

// --- 找回密码页初始化：Start --- //
initCenter.pageResetPsw = function(){
  whatCanIDo(3).then(function(ret){
    if(!ret.success){
      if(ret.err) document.querySelector('#alert-can-not-enroll > .alert-text').innerText = ret.err;
      document.getElementById('alert-can-not-enroll').classList.remove('d-none');
      var btnSubmit = document.querySelector('button[type="submit"]');
      btnSubmit.setAttribute('disabled','disabled');
      btnSubmit.innerText = '暂未开放！'
    }
  })
}
initCenter.formResetPsw = function(formData){
  try{
    formData.logintype = "outside";
    formData.user_type = "outside";
    formData.sid = URL_PARTS.params.sid;
  }catch(e){}
  
  axios.post(this.getAttribute('_action'), formData)
    .then(function(res){
      var retData = res.data || {};
      if(retData.success){
        alert('修改密码成功，请重新登录！', function(){
          location.href = 'index.html';
        });
      }else{
        if(typeof retData.emsg == "string") alert(retData.emsg);
      }
    })
}
// --- 找回密码初始化：End --- //

initCenter.formValidation = function(){
  var forms = document.querySelectorAll('.needs-validation');
  Element.prototype.toggleValid = function(valid){
    if(valid){
      this.classList.add("is-valid");
      this.classList.remove('is-invalid');
    }else{
      this.classList.remove("is-valid");
      this.classList.add('is-invalid');
    }
  }
  Element.prototype.clearValid = function(){
    this.classList.remove("is-valid");
    this.classList.remove('is-invalid');
  }
  var validatePattern = function(pattern, value) {
    var regexPattern = new RegExp(pattern);
    return regexPattern.test(String(value));
  };
  var checkMatch = function(form) {
    var allMatch = true;
    var fn = function(item){
      var target = document.getElementById(item.getAttribute('match')),
          value = item.value;

      if(!target || value != target.value){
        allMatch = false;
        item.toggleValid(false);
        target.toggleValid(false);
      }else{
        item.toggleValid(true);
        target.toggleValid(true);
      }
    }
    if(form.nodeName == 'FORM'){
      form.querySelectorAll('[match]').forEach(fn); //整个表单
    }else{
      if(form.hasAttribute('match')) fn(form); // 单个表单项
    }
    
    return allMatch;
  }

  var checkReadonly = function(form) {
    var allValid = true;
    var fn = function(item){
      var value = item.value;

      if(!value){
        allValid = false;
        item.toggleValid(false);
      }else{
        item.toggleValid(true);
      }
    }
    if(form.nodeName == 'FORM'){
      form.querySelectorAll('[readonly][required]').forEach(fn); //整个表单
    }else{
      if(form.hasAttribute('readonly') && form.hasAttribute('required')) fn(form); // 单个表单项
    }
    
    return allValid;
  }

  var checkPattern = function(form){
    var allValid = true;
    var fn = function(item){
      var pattern = item.getAttribute('pattern'),
          value = item.value;

      if(!validatePattern(pattern, value)){
        allValid = false;
        item.toggleValid(false);
      }else{
        item.toggleValid(true);
      }
    }
    if(form.nodeName == 'FORM'){
      form.querySelectorAll('[pattern]').forEach(fn); //整个表单
    }else{
      if(form.hasAttribute('pattern')) fn(form); // 单个表单项
    }

    return allValid;
  }

  Array.prototype.slice.call(forms)
    .forEach(function (form) {
      form.querySelectorAll('[name]').forEach(function(item){
        $(item).on('change',function(){
          checkMatch(item);
          checkPattern(item);
          checkReadonly(item);
        })
      });

      // 登录
      form.addEventListener('submit', function (event) {
        var valid = true;
        var me = this;
        var btnSubmit = me.querySelector('button[type="submit"]');

        btnSubmit.setAttribute('disabled','disabled');

        event.preventDefault()
        event.stopPropagation()

        this.classList.add('was-validated');
        
        if (!checkMatch(this) || !checkPattern(this) || !checkReadonly(this) || !form.checkValidity()) {
          valid = false;
          btnSubmit.removeAttribute('disabled');
          return;
        }

        var formData = $(this).serializeObject();

        let initFnName = _.camelCase(this.getAttribute('id'));
        if(initFnName && typeof initCenter[initFnName] == 'function'){
          initCenter[initFnName].call(me, formData);
        }

        // 防止多次提交
        setTimeout(function(){
          btnSubmit.removeAttribute('disabled')
        },5000);
      }, false)
    })
}

;(function(){
  // 左侧欢迎词
  updateWelcome();

  // 页面初始化
  let initFnName = _.camelCase(document.body.id);
  if(initFnName && typeof initCenter[initFnName] == 'function') initCenter[initFnName]();

  // 表单校验
  initCenter.formValidation();
})();
